<script setup lang="ts">
import { ref, onMounted, computed, watch, onUnmounted, onBeforeUnmount } from 'vue'
import { useHomeStore } from '@/stores/homeStore'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  Calendar,
  DataLine,
  Platform,
  Filter,
  ArrowDown,
  Search,
  Download,
  Share,
  More,
  Loading,
  Warning,
  PieChart as IconPieChart,
  Connection,
  ChatDotRound,
  Document
} from '@element-plus/icons-vue'
import SentimentTrendAnalysis from '@/components/sentiment/SentimentTrendAnalysis.vue'
import SentimentContentAnalysis from '@/components/sentiment/SentimentContentAnalysis.vue'
import SentimentHeatmapChart from '@/components/sentiment/SentimentHeatmapChart.vue'
import SentimentTopicTrendChart from '@/components/sentiment/SentimentTopicTrendChart.vue'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import type { EChartsType } from 'echarts/core'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer
])

const homeStore = useHomeStore()
const loading = ref(false)

// 时间范围相关
const timeRange = ref('today') // 默认今日
const timeOptions = [
  { key: 'today', label: '今日' },
  { key: 'yesterday', label: '昨日' },
  { key: 'week', label: '本周' },
  { key: 'month', label: '本月' },
  { key: 'custom', label: '自定义' }
]
const dateRange = ref([])

// 平台筛选
const selectedPlatforms = ref<string[]>([])
const platformOptions = computed(() => {
  return homeStore.platformComparison.map(item => ({
    key: item.platform,
    label: item.platform
  }))
})

// 情感类型筛选
const sentimentTypes = ref(['positive', 'neutral', 'negative'])
const sentimentOptions = [
  { key: 'positive', label: '正面', color: '#67C23A' },
  { key: 'neutral', label: '中性', color: '#909399' },
  { key: 'negative', label: '负面', color: '#F56C6C' }
]

// 高峰期分析数据
const peakPeriods = ref([
  { time: '12:00-14:00', type: 'peak', value: 125, change: '+15%' },
  { time: '18:00-20:00', type: 'peak', value: 142, change: '+23%' },
  { time: '03:00-05:00', type: 'low', value: 28, change: '-56%' }
])

// 异常时段标记
const anomalies = ref([
  { time: '2023-11-10 14:30', description: '情感值突然转负', value: -0.76, change: '-46%' },
  { time: '2023-11-11 09:15', description: '正面情感显著提升', value: 0.82, change: '+38%' }
])

// 热点话题情感分布
const topicSentiments = computed(() => {
  // 从热力图数据中提取话题情感分布统计
  if (heatmapData.value.length > 0) {
    const topics = [...new Set(heatmapData.value.map(item => item.topic))].slice(0, 6)
    
    return topics.map(topic => {
      const topicData = heatmapData.value.filter(item => item.topic === topic)
      
      // 计算正面、中性、负面的百分比
      let positive = 0
      let neutral = 0
      let negative = 0
      
      topicData.forEach(item => {
        if (item.sentiment_value > 0.3) {
          positive++
        } else if (item.sentiment_value < -0.3) {
          negative++
        } else {
          neutral++
        }
      })
      
      const total = Math.max(1, positive + neutral + negative)
      
      return {
        topic,
        positive: Math.round((positive / total) * 100),
        neutral: Math.round((neutral / total) * 100),
        negative: Math.round((negative / total) * 100)
      }
    })
  }
  
  // 如果没有数据，返回默认值
  return [
    { topic: '人工智能', positive: 65, neutral: 25, negative: 10 },
    { topic: '数据安全', positive: 30, neutral: 30, negative: 40 },
    { topic: '远程办公', positive: 75, neutral: 15, negative: 10 },
    { topic: '疫情防控', positive: 45, neutral: 30, negative: 25 },
    { topic: '元宇宙', positive: 55, neutral: 30, negative: 15 },
    { topic: '芯片技术', positive: 35, neutral: 25, negative: 40 }
  ]
})

// 定义内容详情的接口
interface ContentDetail {
  id: number;
  content?: string;
  time?: string;
  source?: string;
  author?: string;
  topic?: string;
  heat_value?: number;
  sentiment_value?: number;
  keywords?: string[];
  title?: string;
  value?: number;
}

const currentDetail = ref<ContentDetail | null>(null)

// 活跃标签页
const activeTab = ref('trend')

// 趋势图数据
const trendData = computed(() => {
  // 如果有真实数据则使用真实数据，否则生成模拟数据
  if (homeStore.sentimentTrend && homeStore.sentimentTrend.length > 0) {
    return homeStore.sentimentTrend
  }
  
  // 生成模拟数据
  return generateMockTrendData()
})

// 模拟内容分析数据
const mockContentItems = [
  {
    id: 1,
    content: '人工智能技术的最新突破让我们看到了科技的美好未来，这将大大提升我们的工作效率。',
    time: '2023-11-10 10:30:00',
    source: '微博',
    author: '科技爱好者',
    topic: '人工智能',
    heat_value: 89,
    sentiment_value: 0.85,
    keywords: ['人工智能', '科技', '效率']
  },
  {
    id: 2,
    content: '数据安全事件频发，用户隐私保护形势严峻，企业必须加强安全意识。',
    time: '2023-11-10 11:45:00',
    source: '知乎',
    author: '安全专家',
    topic: '数据安全',
    heat_value: 76,
    sentiment_value: -0.65,
    keywords: ['数据安全', '隐私保护', '安全意识']
  },
  {
    id: 3,
    content: '远程办公模式被越来越多的企业采用，工作生活平衡得到改善。',
    time: '2023-11-10 14:20:00',
    source: '今日头条',
    author: '职场观察',
    topic: '远程办公',
    heat_value: 82,
    sentiment_value: 0.72,
    keywords: ['远程办公', '工作生活平衡', '企业']
  },
  {
    id: 4,
    content: '元宇宙概念股今日大幅波动，投资者需谨慎对待市场炒作行为。',
    time: '2023-11-10 15:30:00',
    source: '财经网',
    author: '投资分析师',
    topic: '元宇宙',
    heat_value: 68,
    sentiment_value: -0.15,
    keywords: ['元宇宙', '概念股', '投资']
  },
  {
    id: 5,
    content: '芯片短缺问题仍未得到有效解决，多家企业生产受到影响，供应链风险上升。',
    time: '2023-11-11 09:15:00',
    source: '新浪财经',
    author: '产业观察家',
    topic: '芯片短缺',
    heat_value: 92,
    sentiment_value: -0.78,
    keywords: ['芯片短缺', '供应链', '风险']
  },
  {
    id: 6,
    content: '数字人民币试点范围进一步扩大，更多城市居民可以体验数字货币的便利。',
    time: '2023-11-11 10:20:00',
    source: '央视新闻',
    author: '财经记者',
    topic: '数字人民币',
    heat_value: 85,
    sentiment_value: 0.62,
    keywords: ['数字人民币', '试点', '数字货币']
  },
  {
    id: 7,
    content: '疫情后旅游业复苏明显，国内多个景区迎来客流高峰，经济活力回升。',
    time: '2023-11-11 11:30:00',
    source: '旅游频道',
    author: '旅游分析师',
    topic: '旅游复苏',
    heat_value: 79,
    sentiment_value: 0.88,
    keywords: ['旅游业', '复苏', '经济']
  },
  {
    id: 8,
    content: '网络安全事件频发，多家企业遭受勒索软件攻击，数据安全形势严峻。',
    time: '2023-11-11 13:45:00',
    source: '安全客',
    author: '网络安全专家',
    topic: '网络安全',
    heat_value: 88,
    sentiment_value: -0.72,
    keywords: ['网络安全', '勒索软件', '数据安全']
  },
  {
    id: 9,
    content: '新能源汽车销量持续走高，市场占有率首次突破30%，绿色出行理念深入人心。',
    time: '2023-11-11 15:10:00',
    source: '汽车之家',
    author: '汽车分析师',
    topic: '新能源汽车',
    heat_value: 83,
    sentiment_value: 0.76,
    keywords: ['新能源汽车', '销量', '绿色出行']
  },
  {
    id: 10,
    content: '全球气候变化加剧，极端天气事件频发，环保压力与日俱增。',
    time: '2023-11-11 16:30:00',
    source: '环球时报',
    author: '环境记者',
    topic: '气候变化',
    heat_value: 90,
    sentiment_value: -0.58,
    keywords: ['气候变化', '极端天气', '环保']
  }
]

// 内容分析数据
const contentData = computed(() => {
  // 如果有真实数据则使用真实数据，否则使用模拟数据
  if (homeStore.hotSentiments && homeStore.hotSentiments.length > 0) {
    // 将 hotSentiments 转换为 ContentDetail 格式
    return homeStore.hotSentiments.map(item => ({
      id: item.id,
      content: item.title,
      time: new Date().toISOString().split('T')[0] + ' ' + Math.floor(Math.random() * 24).toString().padStart(2, '0') + ':' + Math.floor(Math.random() * 60).toString().padStart(2, '0') + ':00',
      source: item.platform,
      author: '未知作者',
      topic: item.title.split(' ')[0],
      heat_value: item.heat_value,
      sentiment_value: item.sentiment_type === 1 ? 0.5 + Math.random() * 0.5 : 
                       item.sentiment_type === -1 ? -0.5 - Math.random() * 0.5 : 
                       -0.2 + Math.random() * 0.4,
      keywords: item.title.split(' ').filter(word => word.length > 1).slice(0, 3)
    }))
  }
  
  // 使用模拟数据
  return mockContentItems
})

// 定义热力图数据项接口
interface HeatmapDataItem {
  id: number;
  topic: string;
  time: string;
  sentiment_value: number;
}

// 热点话题情感分布数据
const heatmapData = computed(() => {
  // 如果有真实数据则使用真实数据，否则生成模拟数据
  if (homeStore.hotSentiments && homeStore.hotSentiments.length > 0) {
    // 将 hotSentiments 转换为 HeatmapDataItem 格式
    const realData: HeatmapDataItem[] = []
    
    // 将数据复制多份，分布在24小时内，以生成更有意义的热力图
    const baseDate = new Date()
    baseDate.setHours(0, 0, 0, 0)
    
    // 常见的话题，确保数据有足够的话题维度
    const commonTopics = [
      '互联网监管政策', 
      '芯片短缺影响产业链', 
      '数字人民币试点扩大', 
      '疫情防控政策实施', 
      '元宇宙概念引发投资热', 
      '远程办公新模式提升效率', 
      '数据安全事件引发公众担忧'
    ]
    
    // 从真实数据中提取话题
    homeStore.hotSentiments.forEach((item, index) => {
      // 提取标题的前几个字作为话题
      const topic = item.title.length > 8 ? item.title.substring(0, 8) : item.title
      
      // 为每个话题在24小时内生成多个数据点
      for (let hour = 0; hour < 24; hour++) {
        // 生成1-5条数据
        const entriesCount = Math.floor(Math.random() * 5) + 1
        
        for (let i = 0; i < entriesCount; i++) {
          const time = new Date(baseDate)
          time.setHours(hour)
          time.setMinutes(Math.floor(Math.random() * 60))
          
          // 根据情感类型生成情感值
          let sentimentValue = 0
          if (item.sentiment_type === 1) {
            sentimentValue = 0.3 + Math.random() * 0.7 // 正面情感 [0.3, 1.0]
          } else if (item.sentiment_type === -1) {
            sentimentValue = -0.3 - Math.random() * 0.7 // 负面情感 [-1.0, -0.3]
          } else {
            sentimentValue = -0.2 + Math.random() * 0.4 // 中性情感 [-0.2, 0.2]
          }
          
          // 添加一些随机波动
          sentimentValue = Math.max(-1, Math.min(1, sentimentValue + (Math.random() * 0.2 - 0.1)))
          
          realData.push({
            id: realData.length + 1,
            topic: topic,
            time: time.toISOString().replace('T', ' ').substring(0, 19),
            sentiment_value: parseFloat(sentimentValue.toFixed(2))
          })
        }
      }
    })
    
    // 如果真实数据的话题不够多，添加一些常见话题以增加热力图的信息量
    if (homeStore.hotSentiments.length < 5) {
      const usedTopics = new Set(realData.map(item => item.topic))
      const remainingTopics = commonTopics.filter(topic => !usedTopics.has(topic))
      
      // 为每个额外话题添加数据
      remainingTopics.slice(0, 5 - homeStore.hotSentiments.length).forEach(topic => {
        // 随机确定情感基准值
        const baseSentiment = Math.random() > 0.5 ? 0.4 : -0.4
        
        for (let hour = 0; hour < 24; hour++) {
          const entriesCount = Math.floor(Math.random() * 3) + 1
          
          for (let i = 0; i < entriesCount; i++) {
            const time = new Date(baseDate)
            time.setHours(hour)
            time.setMinutes(Math.floor(Math.random() * 60))
            
            // 添加一些随机波动
            const sentiment = Math.max(-1, Math.min(1, baseSentiment + (Math.random() * 0.6 - 0.3)))
            
            realData.push({
              id: realData.length + 1,
              topic: topic,
              time: time.toISOString().replace('T', ' ').substring(0, 19),
              sentiment_value: parseFloat(sentiment.toFixed(2))
            })
          }
        }
      })
    }
    
    return realData
  }

  // 生成模拟热力图数据
  return createMockHeatmapData()
})

// 生成模拟热力图数据
const createMockHeatmapData = (): HeatmapDataItem[] => {
  const topics = [
    '互联网监管政策', 
    '芯片短缺影响产业链', 
    '数字人民币试点扩大', 
    '疫情防控政策实施', 
    '元宇宙概念引发投资热', 
    '远程办公新模式提升效率', 
    '数据安全事件引发公众担忧', 
    '最新AI技术突破引发行业热议', 
    '新能源汽车销量持续增长'
  ]
  const mockData: HeatmapDataItem[] = []

  // 生成24小时内的数据
  const baseDate = new Date()
  baseDate.setHours(0, 0, 0, 0)

  // 为每个话题设置基本情感倾向和时间特征
  type TopicSettings = {
    baseSentiment: number;
    peakHours: number[];
    variance: number;
  }
  
  const topicSettings: Record<string, TopicSettings> = {
    '互联网监管政策': { baseSentiment: -0.3, peakHours: [9, 15, 20], variance: 0.4 },
    '芯片短缺影响产业链': { baseSentiment: -0.6, peakHours: [10, 14, 22], variance: 0.3 },
    '数字人民币试点扩大': { baseSentiment: 0.5, peakHours: [8, 12, 18], variance: 0.5 },
    '疫情防控政策实施': { baseSentiment: 0.1, peakHours: [7, 12, 19], variance: 0.6 },
    '元宇宙概念引发投资热': { baseSentiment: 0.7, peakHours: [10, 14, 21], variance: 0.3 },
    '远程办公新模式提升效率': { baseSentiment: 0.4, peakHours: [8, 11, 16], variance: 0.4 },
    '数据安全事件引发公众担忧': { baseSentiment: -0.7, peakHours: [9, 13, 20], variance: 0.3 },
    '最新AI技术突破引发行业热议': { baseSentiment: 0.8, peakHours: [10, 15, 22], variance: 0.2 },
    '新能源汽车销量持续增长': { baseSentiment: 0.6, peakHours: [9, 14, 19], variance: 0.3 }
  }

  for (let hour = 0; hour < 24; hour++) {
    // 为每个话题每小时生成数据
    topics.forEach(topic => {
      const settings = topicSettings[topic] || { baseSentiment: 0, peakHours: [12], variance: 0.5 }
      // 根据是否是高峰时段决定生成的数据量
      const isPeakHour = settings.peakHours.includes(hour)
      const entriesCount = isPeakHour ? 
        Math.floor(Math.random() * 8) + 3 : // 高峰时段 3-10 条
        Math.floor(Math.random() * 5) + 1   // 非高峰时段 1-5 条
      
      for (let i = 0; i < entriesCount; i++) {
        const time = new Date(baseDate)
        time.setHours(hour)
        time.setMinutes(Math.floor(Math.random() * 60))
        
        // 根据时段调整情感值
        // 早晨情感较积极，午后略微下降，晚间波动较大
        let timeAdjustment = 0
        if (hour >= 6 && hour < 12) {
          timeAdjustment = 0.1 // 早晨情感略微积极
        } else if (hour >= 12 && hour < 18) {
          timeAdjustment = -0.05 // 午后情感略微消极
        } else {
          timeAdjustment = (Math.random() * 0.3) - 0.15 // 晚间随机波动
        }
        
        // 高峰时段情感波动更大
        const volatility = isPeakHour ? settings.variance : settings.variance * 0.5
        
        // 计算最终情感值
        let sentiment = settings.baseSentiment + timeAdjustment + (Math.random() * volatility * 2 - volatility)
        
        // 确保情感值在-1到1之间
        sentiment = Math.max(-1, Math.min(1, sentiment))
        
        mockData.push({
          id: mockData.length + 1,
          topic,
          time: time.toISOString().replace('T', ' ').substring(0, 19),
          sentiment_value: parseFloat(sentiment.toFixed(2))
        })
      }
    })
  }
  
  return mockData
}

// 极端情感案例
const extremeCases = computed(() => {
  // 如果没有数据，提供默认值
  const defaultCase: ContentDetail = {
    id: 0,
    title: '',
    content: '',
    time: '',
    source: '',
    sentiment_value: 0,
    value: 0
  };
  
  // 将 extremeSentiment 中的数据转换为 ContentDetail 格式
  const positive = homeStore.extremeSentiment?.most_positive 
    ? {
        id: homeStore.extremeSentiment.most_positive.id,
        title: homeStore.extremeSentiment.most_positive.title,
        content: homeStore.extremeSentiment.most_positive.title, // 使用 title 作为 content
        time: '未知',
        source: '未知',
        sentiment_value: homeStore.extremeSentiment.most_positive.value,
        value: homeStore.extremeSentiment.most_positive.value
      }
    : defaultCase;
    
  const negative = homeStore.extremeSentiment?.most_negative
    ? {
        id: homeStore.extremeSentiment.most_negative.id,
        title: homeStore.extremeSentiment.most_negative.title,
        content: homeStore.extremeSentiment.most_negative.title, // 使用 title 作为 content
        time: '未知',
        source: '未知',
        sentiment_value: homeStore.extremeSentiment.most_negative.value,
        value: homeStore.extremeSentiment.most_negative.value
      }
    : defaultCase;
  
  return { positive, negative }
})

// 内容详情模态框
const detailDialogVisible = ref(false)

// 生成模拟趋势数据
const generateMockTrendData = () => {
  const now = new Date()
  const data = []
  
  // 生成过去24小时的数据
  for (let i = 23; i >= 0; i--) {
    const time = new Date(now)
    time.setHours(now.getHours() - i)
    
    const hourStr = time.getHours().toString().padStart(2, '0')
    const dateStr = `${time.getMonth() + 1}-${time.getDate()} ${hourStr}:00`
    
    // 生成随机数据，但保持一定的趋势性
    const basePositive = 30 + Math.sin(i / 3) * 15
    const baseNegative = 20 + Math.cos(i / 4) * 10
    const baseNeutral = 50 - Math.sin(i / 5) * 10
    
    data.push({
      date: dateStr,
      positive: Math.round(basePositive + Math.random() * 10),
      negative: Math.round(baseNegative + Math.random() * 8),
      neutral: Math.round(baseNeutral + Math.random() * 15)
    })
  }
  
  return data
}

// 是否显示加载动画
const isLoading = ref(false)

// 是否自动刷新
const autoRefresh = ref(false)
const refreshInterval = ref(60) // 默认60秒

// 自动刷新定时器
let refreshTimer: number | null = null

// 开始自动刷新
const startAutoRefresh = () => {
  stopAutoRefresh() // 先停止现有的定时器
  
  refreshTimer = window.setInterval(() => {
    refreshData()
  }, refreshInterval.value * 1000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer !== null) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 监听自动刷新状态变化
watch(autoRefresh, (newValue) => {
  if (newValue) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
})

// 监听刷新间隔变化
watch(refreshInterval, () => {
  if (autoRefresh.value) {
    startAutoRefresh() // 重新启动定时器
  }
})

// 刷新数据
const refreshData = async () => {
  isLoading.value = true
  loading.value = true
  try {
    await homeStore.fetchHomeData()
    ElMessage.success('数据已更新')
  } catch (error) {
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
    isLoading.value = false
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  stopAutoRefresh()
})

// 应用筛选条件
const applyFilters = () => {
  isLoading.value = true
  loading.value = true
  // 模拟应用筛选条件
  setTimeout(() => {
    ElMessage.success('筛选条件已应用')
    loading.value = false
    isLoading.value = false
  }, 1000)
}

// 导出数据
const exportData = () => {
  ElMessage.success('数据导出功能已触发')
  
  // 根据当前活跃的标签页导出不同的数据
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  let filename = ''
  let exportData = {}
  
  switch (activeTab.value) {
    case 'trend':
      filename = `情感趋势分析_${timestamp}.json`
      exportData = { trendData: trendData.value }
      break
    case 'content':
      filename = `情感内容分析_${timestamp}.json`
      exportData = { contentData: contentData.value }
      break
    case 'heatmap':
      filename = `情感热力图_${timestamp}.json`
      exportData = { heatmapData: heatmapData.value }
      break
    default:
      filename = `情感分析数据_${timestamp}.json`
      exportData = {
        trendData: trendData.value,
        contentData: contentData.value,
        heatmapData: heatmapData.value
      }
  }
  
  // 创建下载
  const jsonStr = JSON.stringify(exportData, null, 2)
  const blob = new Blob([jsonStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 查看详情
const viewDetail = (item: any) => {
  currentDetail.value = item
  detailDialogVisible.value = true
}

// 情感分析详情
const showSentimentDetailDialog = ref(false)
const sentimentDetailTab = ref('distribution')
const sentimentType = ref('all')
const sentimentWordCloudData = ref([
  { name: '满意', value: 87, sentiment: 'positive' },
  { name: '喜欢', value: 78, sentiment: 'positive' },
  { name: '优秀', value: 65, sentiment: 'positive' },
  { name: '推荐', value: 56, sentiment: 'positive' },
  { name: '好评', value: 52, sentiment: 'positive' },
  { name: '高质量', value: 48, sentiment: 'positive' },
  { name: '不错', value: 45, sentiment: 'positive' },
  { name: '一般', value: 67, sentiment: 'neutral' },
  { name: '还可以', value: 58, sentiment: 'neutral' },
  { name: '中等', value: 46, sentiment: 'neutral' },
  { name: '凑合', value: 42, sentiment: 'neutral' },
  { name: '普通', value: 38, sentiment: 'neutral' },
  { name: '差评', value: 72, sentiment: 'negative' },
  { name: '失望', value: 65, sentiment: 'negative' },
  { name: '问题', value: 58, sentiment: 'negative' },
  { name: '退款', value: 52, sentiment: 'negative' },
  { name: '糟糕', value: 46, sentiment: 'negative' },
  { name: '不满', value: 42, sentiment: 'negative' },
  { name: '超赞', value: 92, sentiment: 'positive' },
  { name: '完美', value: 85, sentiment: 'positive' },
  { name: '棒极了', value: 80, sentiment: 'positive' },
  { name: '失败', value: 68, sentiment: 'negative' },
  { name: '垃圾', value: 63, sentiment: 'negative' },
  { name: '难用', value: 60, sentiment: 'negative' },
  { name: '一般般', value: 55, sentiment: 'neutral' },
  { name: '还行', value: 52, sentiment: 'neutral' },
  { name: '不确定', value: 45, sentiment: 'neutral' }
])

// 根据选择的情感类型过滤词云数据
const filteredWordCloudData = computed(() => {
  if (sentimentType.value === 'all') {
    return sentimentWordCloudData.value
  }
  return sentimentWordCloudData.value.filter(word => word.sentiment === sentimentType.value)
})

// 按出现次数排序的词云数据
const sortedWordCloudData = computed(() => {
  return [...filteredWordCloudData.value].sort((a, b) => b.value - a.value)
})

// 情感分布详情
const sentimentDistributionDetail = computed(() => {
  // 如果有真实数据则使用真实数据，否则使用模拟数据
  if (homeStore.sentimentDistribution) {
    return {
      positive: homeStore.sentimentDistribution.positive || 0,
      neutral: homeStore.sentimentDistribution.neutral || 0,
      negative: homeStore.sentimentDistribution.negative || 0
    }
  }
  
  // 使用模拟数据
  return {
    positive: 568,
    neutral: 423,
    negative: 267
  }
})

// 计算情感分布百分比
const sentimentPercentage = computed(() => {
  const total = sentimentDistributionDetail.value.positive + 
               sentimentDistributionDetail.value.neutral + 
               sentimentDistributionDetail.value.negative
  
  if (total === 0) return { positive: 0, neutral: 0, negative: 0 }
  
  return {
    positive: Math.round(sentimentDistributionDetail.value.positive / total * 100),
    neutral: Math.round(sentimentDistributionDetail.value.neutral / total * 100),
    negative: Math.round(sentimentDistributionDetail.value.negative / total * 100)
  }
})

// 情感强度分布
const sentimentIntensityData = ref({
  strongPositive: 235, // 强烈正面
  moderatePositive: 186, // 中等正面
  mildPositive: 147, // 轻微正面
  neutral: 423, // 中性
  mildNegative: 98, // 轻微负面
  moderateNegative: 102, // 中等负面
  strongNegative: 67 // 强烈负面
})

// 情感时段分布数据
const sentimentTimeDistribution = computed(() => {
  // 生成24小时的情感分布数据
  const data = []
  for (let hour = 0; hour < 24; hour++) {
    const hourStr = hour.toString().padStart(2, '0')
    
    // 根据时间段生成不同的情感分布
    let positive, neutral, negative
    
    if (hour >= 7 && hour <= 10) {
      // 早晨情感较正面
      positive = 40 + Math.floor(Math.random() * 20)
      negative = 10 + Math.floor(Math.random() * 15)
      neutral = 100 - positive - negative
    } else if (hour >= 12 && hour <= 14) {
      // 午休时间情感较平和
      neutral = 40 + Math.floor(Math.random() * 20)
      positive = 30 + Math.floor(Math.random() * 15)
      negative = 100 - positive - neutral
    } else if (hour >= 17 && hour <= 22) {
      // 晚上情感波动较大
      if (hour % 2 === 0) {
        positive = 45 + Math.floor(Math.random() * 20)
        negative = 20 + Math.floor(Math.random() * 15)
      } else {
        positive = 30 + Math.floor(Math.random() * 15)
        negative = 35 + Math.floor(Math.random() * 20)
      }
      neutral = 100 - positive - negative
    } else {
      // 深夜/凌晨情感较负面
      negative = 35 + Math.floor(Math.random() * 20)
      neutral = 35 + Math.floor(Math.random() * 20)
      positive = 100 - negative - neutral
    }
    
    data.push({
      time: `${hourStr}:00`,
      positive,
      neutral,
      negative
    })
  }
  
  return data
})

// 打开情感分析详情
const openSentimentDetail = () => {
  showSentimentDetailDialog.value = true
}

// 导出情感分析详情
const exportSentimentDetail = () => {
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  const filename = `情感分析详情_${timestamp}.json`
  
  const exportData = {
    distribution: sentimentDistributionDetail.value,
    percentage: sentimentPercentage.value,
    intensity: sentimentIntensityData.value,
    wordCloud: sentimentWordCloudData.value,
    timeDistribution: sentimentTimeDistribution.value
  }
  
  // 创建下载
  const jsonStr = JSON.stringify(exportData, null, 2)
  const blob = new Blob([jsonStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('情感分析详情数据已导出')
}

// 情感分析详情对话框
const sentimentDetailDialogVisible = computed({
  get: () => showSentimentDetailDialog.value,
  set: (value) => { showSentimentDetailDialog.value = value }
})

// 添加饼图相关的ref和方法
const sentimentPieChartRef = ref<HTMLElement | null>(null)
let sentimentPieChart: EChartsType | null = null

// 初始化情感分布饼图
const initSentimentPieChart = () => {
  if (!sentimentPieChartRef.value) return
  
  // 销毁之前的实例
  if (sentimentPieChart) {
    sentimentPieChart.dispose()
  }
  
  // 创建图表实例
  sentimentPieChart = echarts.init(sentimentPieChartRef.value)
  
  // 设置图表选项
  const option = {
    title: {
      text: '情感分布比例',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: ['正面', '中性', '负面']
    },
    series: [
      {
        name: '情感分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: [
          { value: sentimentPercentage.value.positive, name: '正面', itemStyle: { color: '#67C23A' } },
          { value: sentimentPercentage.value.neutral, name: '中性', itemStyle: { color: '#909399' } },
          { value: sentimentPercentage.value.negative, name: '负面', itemStyle: { color: '#F56C6C' } }
        ]
      }
    ]
  }
  
  sentimentPieChart.setOption(option)
}

// 监听情感分析详情对话框的显示状态
watch(showSentimentDetailDialog, (newVal) => {
  if (newVal) {
    // 在对话框显示后，初始化饼图
    setTimeout(() => {
      initSentimentPieChart()
    }, 100)
  }
})

// 监听标签页切换
watch(sentimentDetailTab, (newVal) => {
  if (newVal === 'distribution' && showSentimentDetailDialog.value) {
    // 在切换到分布标签页时，重新初始化饼图
    setTimeout(() => {
      initSentimentPieChart()
    }, 100)
  }
})

// 添加resize处理函数，避免内联函数导致的事件监听器问题
const handleResize = () => {
  if (sentimentPieChart) {
    sentimentPieChart.resize()
  }
}

// 监听窗口大小变化
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (sentimentPieChart) {
    sentimentPieChart.dispose()
    sentimentPieChart = null
  }
})

onMounted(async () => {
  if (!homeStore.lastUpdate) {
    await homeStore.fetchHomeData()
  }
})

// 监听标签页切换，确保热力图正确渲染
watch(activeTab, (newVal) => {
  if (newVal === 'heatmap') {
    // 在切换到热力图标签页时，触发一次窗口大小变化事件，以确保图表正确渲染
    setTimeout(() => {
      window.dispatchEvent(new Event('resize'))
    }, 100)
  }
})

// 添加新的变量来控制图表类型
const chartType = ref('line')

// 监听图表类型变化，确保图表正确渲染
watch(chartType, () => {
  setTimeout(() => {
    window.dispatchEvent(new Event('resize'))
  }, 100)
})
</script>

<template>
  <div class="sentiment-analysis-container">
    <!-- 页面标题和控制区 -->
    <div class="page-header">
      <h1 class="page-title">情感详情分析</h1>
      <div class="header-actions">
        <div class="refresh-controls">
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            inactive-text=""
            style="margin-right: 10px;"
          />
          <el-select 
            v-model="refreshInterval" 
            size="small" 
            style="width: 100px; margin-right: 15px;"
            :disabled="!autoRefresh"
          >
            <el-option :value="30" label="30秒" />
            <el-option :value="60" label="1分钟" />
            <el-option :value="300" label="5分钟" />
            <el-option :value="600" label="10分钟" />
          </el-select>
          <el-button type="primary" :icon="Refresh" :loading="loading" @click="refreshData">
            刷新数据
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 全局加载状态 -->
    <div class="loading-overlay" v-if="isLoading">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <div class="loading-text">数据加载中...</div>
    </div>
    
    <!-- 筛选条件面板 -->
    <el-card class="filter-panel" shadow="hover">
      <template #header>
        <div class="filter-header">
          <span><el-icon><Filter /></el-icon> 筛选条件</span>
          <el-button type="primary" size="small" @click="applyFilters">应用筛选</el-button>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="filter-item">
            <div class="filter-label">时间范围</div>
            <el-select v-model="timeRange" class="filter-select">
              <el-option
                v-for="item in timeOptions"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              />
            </el-select>
            <el-date-picker
              v-if="timeRange === 'custom'"
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="margin-top: 10px; width: 100%;"
            />
          </div>
        </el-col>
        
        <el-col :span="8">
          <div class="filter-item">
            <div class="filter-label">平台选择</div>
            <el-select v-model="selectedPlatforms" multiple collapse-tags class="filter-select">
              <el-option
                v-for="item in platformOptions"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              />
            </el-select>
          </div>
        </el-col>
        
        <el-col :span="8">
          <div class="filter-item">
            <div class="filter-label">情感类型</div>
            <el-checkbox-group v-model="sentimentTypes">
              <el-checkbox v-for="item in sentimentOptions" :key="item.key" :label="item.key">
                <span :style="{ color: item.color }">{{ item.label }}</span>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 内容区域 -->
    <div class="content-area">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 时间维度分析 -->
        <el-tab-pane label="时间维度分析" name="trend">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-card class="chart-card">
                  <template #header>
                    <div class="card-header">
                      <span>情感趋势分析</span>
                      <div class="header-actions">
                        <el-radio-group v-model="timeRange" size="small">
                          <el-radio-button label="today">今日</el-radio-button>
                          <el-radio-button label="week">本周</el-radio-button>
                          <el-radio-button label="month">本月</el-radio-button>
                        </el-radio-group>
                      </div>
                    </div>
                  </template>
                  <SentimentTrendAnalysis 
                    :data="trendData" 
                    :time-unit="timeRange === 'today' ? 'hour' : timeRange === 'week' ? 'day' : 'day'"
                    height="400px"
                  />
                </el-card>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="12">
                <el-card class="info-card">
                  <template #header>
                    <div class="card-header">
                      <span>高峰期分析</span>
                    </div>
                  </template>
                  <div class="peak-analysis">
                    <div v-for="(item, index) in peakPeriods" :key="index" class="peak-item" :class="item.type">
                      <div class="peak-icon">
                        <el-icon v-if="item.type === 'peak'"><ArrowDown style="transform: rotate(180deg);" /></el-icon>
                        <el-icon v-else><ArrowDown /></el-icon>
                      </div>
                      <div class="peak-info">
                        <div class="peak-time">{{ item.time }}</div>
                        <div class="peak-value">数据量: {{ item.value }}</div>
                        <div class="peak-change">变化率: {{ item.change }}</div>
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              
              <el-col :span="12">
                <el-card class="info-card">
                  <template #header>
                    <div class="card-header">
                      <span>异常时段标记</span>
                    </div>
                  </template>
                  <div class="anomaly-list">
                    <el-timeline>
                      <el-timeline-item
                        v-for="(item, index) in anomalies"
                        :key="index"
                        :type="item.value > 0 ? 'success' : 'danger'"
                        :timestamp="item.time"
                      >
                        <div class="anomaly-content">
                          <div class="anomaly-description">{{ item.description }}</div>
                          <div class="anomaly-value" :class="{ positive: item.value > 0, negative: item.value < 0 }">
                            情感值: {{ item.value.toFixed(2) }} ({{ item.change }})
                          </div>
                        </div>
                      </el-timeline-item>
                    </el-timeline>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        
        <!-- 内容维度分析 -->
        <el-tab-pane label="内容维度分析" name="content">
          <div class="tab-content">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>情感内容分析</span>
                </div>
              </template>
              <SentimentContentAnalysis 
                :data="contentData" 
                @view-detail="viewDetail"
              />
            </el-card>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="12">
                <el-card class="info-card">
                  <template #header>
                    <div class="card-header">
                      <span>极端正面情感案例</span>
                    </div>
                  </template>
                  <div class="extreme-case positive" v-if="extremeCases.positive">
                    <div class="case-content">{{ extremeCases.positive.content }}</div>
                    <div class="case-meta">
                      <div class="case-source">来源: {{ extremeCases.positive.source }}</div>
                      <div class="case-time">时间: {{ extremeCases.positive.time }}</div>
                      <div class="case-value">情感值: {{ extremeCases.positive.sentiment_value }}</div>
                    </div>
                  </div>
                  <el-empty v-else description="暂无数据" />
                </el-card>
              </el-col>
              
              <el-col :span="12">
                <el-card class="info-card">
                  <template #header>
                    <div class="card-header">
                      <span>极端负面情感案例</span>
                    </div>
                  </template>
                  <div class="extreme-case negative" v-if="extremeCases.negative">
                    <div class="case-content">{{ extremeCases.negative.content }}</div>
                    <div class="case-meta">
                      <div class="case-source">来源: {{ extremeCases.negative.source }}</div>
                      <div class="case-time">时间: {{ extremeCases.negative.time }}</div>
                      <div class="case-value">情感值: {{ extremeCases.negative.sentiment_value }}</div>
                    </div>
                  </div>
                  <el-empty v-else description="暂无数据" />
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        
        <!-- 热点话题情感分布 -->
        <el-tab-pane label="热点话题情感分布" name="heatmap">
          <div class="tab-content">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>热点话题情感趋势图</span>
                  <div class="chart-controls">
                    <el-radio-group v-model="chartType" size="small">
                      <el-radio-button label="line">折线图</el-radio-button>
                      <el-radio-button label="heatmap">热力图</el-radio-button>
                    </el-radio-group>
                  </div>
                </div>
              </template>
              <div class="chart-container">
                <div v-if="chartType === 'line'" class="trend-chart-container">
                  <SentimentTopicTrendChart 
                    :data="heatmapData" 
                    height="600px"
                    title="热点话题情感趋势"
                  />
                </div>
                <div v-else class="heatmap-container">
                  <SentimentHeatmapChart 
                    :data="heatmapData" 
                    height="600px"
                  />
                </div>
              </div>
            </el-card>
            
            <el-card class="info-card" style="margin-top: 20px;">
              <template #header>
                <div class="card-header">
                  <span>热点话题情感分布统计</span>
                </div>
              </template>
              <div class="topic-sentiment-stats">
                <div v-for="(item, index) in topicSentiments" :key="index" class="topic-item">
                  <div class="topic-name">{{ item.topic }}</div>
                  <div class="topic-bars">
                    <div class="sentiment-bar">
                      <div class="bar-label">正面</div>
                      <el-progress :percentage="item.positive" :color="'#67C23A'" :format="() => `${item.positive}%`" />
                    </div>
                    <div class="sentiment-bar">
                      <div class="bar-label">中性</div>
                      <el-progress :percentage="item.neutral" :color="'#909399'" :format="() => `${item.neutral}%`" />
                    </div>
                    <div class="sentiment-bar">
                      <div class="bar-label">负面</div>
                      <el-progress :percentage="item.negative" :color="'#F56C6C'" :format="() => `${item.negative}%`" />
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 导出数据按钮 -->
    <div class="export-actions">
      <el-button type="primary" :icon="IconPieChart" @click="openSentimentDetail" style="margin-right: 10px;">
        情感分析详情
      </el-button>
      <el-button type="success" :icon="Download" @click="exportData">导出分析数据</el-button>
    </div>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="情感详情"
      width="60%"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="内容">{{ currentDetail.content || '暂无内容' }}</el-descriptions-item>
          <el-descriptions-item label="来源">{{ currentDetail.source || '未知来源' }}</el-descriptions-item>
          <el-descriptions-item label="时间">{{ currentDetail.time || '未知时间' }}</el-descriptions-item>
          <el-descriptions-item label="话题">{{ currentDetail.topic || '未分类' }}</el-descriptions-item>
          <el-descriptions-item label="情感值">
            <span :class="{ 
              'positive-text': currentDetail.sentiment_value && currentDetail.sentiment_value > 0.2, 
              'negative-text': currentDetail.sentiment_value && currentDetail.sentiment_value < -0.2 
            }">
              {{ currentDetail.sentiment_value ? currentDetail.sentiment_value.toFixed(2) : '0.00' }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="热度" v-if="currentDetail.heat_value !== undefined">
            <el-progress 
              :percentage="currentDetail.heat_value" 
              :color="
                currentDetail.heat_value > 80 ? '#F56C6C' : 
                currentDetail.heat_value > 60 ? '#E6A23C' : '#409EFF'
              "
            />
          </el-descriptions-item>
          <el-descriptions-item label="热度" v-else>
            <span>暂无热度数据</span>
          </el-descriptions-item>
          <el-descriptions-item label="关键词" v-if="currentDetail.keywords && currentDetail.keywords.length">
            <el-tag 
              v-for="(keyword, index) in currentDetail.keywords" 
              :key="index"
              style="margin-right: 5px;"
            >
              {{ keyword }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="关键词" v-else>
            <span>暂无关键词</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" :icon="Download">导出</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 情感分析详情对话框 -->
    <el-dialog
      v-model="sentimentDetailDialogVisible"
      title="情感分析详情"
      width="80%"
      destroy-on-close
      top="5vh"
    >
      <el-tabs v-model="sentimentDetailTab" type="border-card">
        <el-tab-pane label="情感分布统计" name="distribution">
          <div class="sentiment-detail-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="sentiment-distribution-card">
                  <h3 class="sentiment-card-title">情感总体分布</h3>
                  <div class="distribution-chart">
                    <div class="distribution-item">
                      <div class="distribution-label positive">正面情感</div>
                      <div class="distribution-value">{{ sentimentDistributionDetail.positive }} ({{ sentimentPercentage.positive }}%)</div>
                      <el-progress 
                        :percentage="sentimentPercentage.positive" 
                        :color="'#67C23A'"
                        :show-text="false"
                        :stroke-width="20"
                      />
                    </div>
                    <div class="distribution-item">
                      <div class="distribution-label neutral">中性情感</div>
                      <div class="distribution-value">{{ sentimentDistributionDetail.neutral }} ({{ sentimentPercentage.neutral }}%)</div>
                      <el-progress 
                        :percentage="sentimentPercentage.neutral" 
                        :color="'#909399'"
                        :show-text="false"
                        :stroke-width="20"
                      />
                    </div>
                    <div class="distribution-item">
                      <div class="distribution-label negative">负面情感</div>
                      <div class="distribution-value">{{ sentimentDistributionDetail.negative }} ({{ sentimentPercentage.negative }}%)</div>
                      <el-progress 
                        :percentage="sentimentPercentage.negative" 
                        :color="'#F56C6C'"
                        :show-text="false"
                        :stroke-width="20"
                      />
                    </div>
                  </div>
                  
                  <div class="sentiment-pie-chart">
                    <div ref="sentimentPieChartRef" style="width: 100%; height: 300px;"></div>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="sentiment-distribution-card">
                  <h3 class="sentiment-card-title">情感强度分布</h3>
                  <div class="intensity-chart">
                    <div class="intensity-item">
                      <div class="intensity-label strong-positive">强烈正面</div>
                      <div class="intensity-value">{{ sentimentIntensityData.strongPositive }}</div>
                      <el-progress 
                        :percentage="Math.round(sentimentIntensityData.strongPositive / 10)" 
                        :color="'#67C23A'"
                        :show-text="false"
                        :stroke-width="15"
                      />
                    </div>
                    <div class="intensity-item">
                      <div class="intensity-label moderate-positive">中等正面</div>
                      <div class="intensity-value">{{ sentimentIntensityData.moderatePositive }}</div>
                      <el-progress 
                        :percentage="Math.round(sentimentIntensityData.moderatePositive / 10)" 
                        :color="'#95D475'"
                        :show-text="false"
                        :stroke-width="15"
                      />
                    </div>
                    <div class="intensity-item">
                      <div class="intensity-label mild-positive">轻微正面</div>
                      <div class="intensity-value">{{ sentimentIntensityData.mildPositive }}</div>
                      <el-progress 
                        :percentage="Math.round(sentimentIntensityData.mildPositive / 10)" 
                        :color="'#B3E19D'"
                        :show-text="false"
                        :stroke-width="15"
                      />
                    </div>
                    <div class="intensity-item">
                      <div class="intensity-label neutral">中性</div>
                      <div class="intensity-value">{{ sentimentIntensityData.neutral }}</div>
                      <el-progress 
                        :percentage="Math.round(sentimentIntensityData.neutral / 10)" 
                        :color="'#909399'"
                        :show-text="false"
                        :stroke-width="15"
                      />
                    </div>
                    <div class="intensity-item">
                      <div class="intensity-label mild-negative">轻微负面</div>
                      <div class="intensity-value">{{ sentimentIntensityData.mildNegative }}</div>
                      <el-progress 
                        :percentage="Math.round(sentimentIntensityData.mildNegative / 10)" 
                        :color="'#F9A7A7'"
                        :show-text="false"
                        :stroke-width="15"
                      />
                    </div>
                    <div class="intensity-item">
                      <div class="intensity-label moderate-negative">中等负面</div>
                      <div class="intensity-value">{{ sentimentIntensityData.moderateNegative }}</div>
                      <el-progress 
                        :percentage="Math.round(sentimentIntensityData.moderateNegative / 10)" 
                        :color="'#F78989'"
                        :show-text="false"
                        :stroke-width="15"
                      />
                    </div>
                    <div class="intensity-item">
                      <div class="intensity-label strong-negative">强烈负面</div>
                      <div class="intensity-value">{{ sentimentIntensityData.strongNegative }}</div>
                      <el-progress 
                        :percentage="Math.round(sentimentIntensityData.strongNegative / 10)" 
                        :color="'#F56C6C'"
                        :show-text="false"
                        :stroke-width="15"
                      />
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="24">
                <div class="sentiment-distribution-card">
                  <h3 class="sentiment-card-title">情感时段分布</h3>
                  <div class="time-distribution-chart">
                    <el-table :data="sentimentTimeDistribution" style="width: 100%" :max-height="400" stripe>
                      <el-table-column prop="time" label="时间段" width="100" />
                      <el-table-column label="正面情感" width="180">
                        <template #default="scope">
                          <el-progress 
                            :percentage="scope.row.positive" 
                            :color="'#67C23A'" 
                            :format="() => `${scope.row.positive}%`"
                            :stroke-width="12"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="中性情感" width="180">
                        <template #default="scope">
                          <el-progress 
                            :percentage="scope.row.neutral" 
                            :color="'#909399'" 
                            :format="() => `${scope.row.neutral}%`"
                            :stroke-width="12"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="负面情感">
                        <template #default="scope">
                          <el-progress 
                            :percentage="scope.row.negative" 
                            :color="'#F56C6C'" 
                            :format="() => `${scope.row.negative}%`"
                            :stroke-width="12"
                          />
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="情感词云分析" name="wordcloud">
          <div class="sentiment-detail-content">
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="sentiment-distribution-card">
                  <h3 class="sentiment-card-title">情感词云</h3>
                  <div class="word-cloud-tabs">
                    <el-radio-group v-model="sentimentType" size="large">
                      <el-radio-button label="all">全部</el-radio-button>
                      <el-radio-button label="positive">正面</el-radio-button>
                      <el-radio-button label="neutral">中性</el-radio-button>
                      <el-radio-button label="negative">负面</el-radio-button>
                    </el-radio-group>
                  </div>
                  
                  <div class="word-cloud-container">
                    <div class="word-cloud-list">
                      <div 
                        v-for="(word, index) in filteredWordCloudData" 
                        :key="index" 
                        class="word-cloud-item"
                        :class="word.sentiment"
                        :style="{
                          fontSize: `${Math.max(14, Math.min(28, 14 + word.value / 6))}px`,
                          fontWeight: word.value > 60 ? 'bold' : 'normal',
                          padding: `${Math.max(5, Math.min(12, 5 + word.value / 20))}px ${Math.max(10, Math.min(20, 10 + word.value / 15))}px`
                        }"
                      >
                        {{ word.name }}
                        <span class="word-value">({{ word.value }})</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="24">
                <div class="sentiment-distribution-card">
                  <h3 class="sentiment-card-title">热门情感词汇</h3>
                  <el-table :data="sortedWordCloudData.slice(0, 10)" style="width: 100%">
                    <el-table-column prop="name" label="词汇" width="180" />
                    <el-table-column prop="sentiment" label="情感类型" width="180">
                      <template #default="scope">
                        <el-tag 
                          :type="scope.row.sentiment === 'positive' ? 'success' : 
                                scope.row.sentiment === 'negative' ? 'danger' : 'info'"
                        >
                          {{ scope.row.sentiment === 'positive' ? '正面' : 
                             scope.row.sentiment === 'negative' ? '负面' : '中性' }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="value" label="出现次数" />
                    <el-table-column label="热度">
                      <template #default="scope">
                        <el-progress 
                          :percentage="Math.min(100, Math.round(scope.row.value))"
                          :color="scope.row.sentiment === 'positive' ? '#67C23A' : 
                                 scope.row.sentiment === 'negative' ? '#F56C6C' : '#909399'"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="情感来源分析" name="source">
          <div class="sentiment-detail-content">
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="sentiment-distribution-card">
                  <h3 class="sentiment-card-title">平台情感分布</h3>
                  <div class="platform-sentiment-chart">
                    <el-table :data="[
                      { platform: '微博', positive: 65, neutral: 20, negative: 15 },
                      { platform: '知乎', positive: 45, neutral: 35, negative: 20 },
                      { platform: '今日头条', positive: 55, neutral: 25, negative: 20 },
                      { platform: '抖音', positive: 70, neutral: 15, negative: 15 },
                      { platform: '微信', positive: 60, neutral: 30, negative: 10 },
                      { platform: '小红书', positive: 75, neutral: 15, negative: 10 }
                    ]" style="width: 100%">
                      <el-table-column prop="platform" label="平台" width="180" />
                      <el-table-column label="情感分布">
                        <template #default="scope">
                          <div class="stacked-progress">
                            <div class="stacked-segment positive" :style="{ width: scope.row.positive + '%' }">
                              {{ scope.row.positive }}%
                            </div>
                            <div class="stacked-segment neutral" :style="{ width: scope.row.neutral + '%' }">
                              {{ scope.row.neutral }}%
                            </div>
                            <div class="stacked-segment negative" :style="{ width: scope.row.negative + '%' }">
                              {{ scope.row.negative }}%
                            </div>
                          </div>
                          <div class="progress-legend">
                            <span class="legend-item positive">正面</span>
                            <span class="legend-item neutral">中性</span>
                            <span class="legend-item negative">负面</span>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </el-col>
            </el-row>
            
            <el-row :gutter="20" style="margin-top: 20px;">
              <el-col :span="24">
                <div class="sentiment-distribution-card">
                  <h3 class="sentiment-card-title">用户群体情感分析</h3>
                  <div class="user-group-sentiment">
                    <el-table :data="[
                      { group: '18-24岁', positive: 72, neutral: 18, negative: 10, count: 342 },
                      { group: '25-34岁', positive: 58, neutral: 27, negative: 15, count: 586 },
                      { group: '35-44岁', positive: 45, neutral: 35, negative: 20, count: 423 },
                      { group: '45-54岁', positive: 40, neutral: 30, negative: 30, count: 287 },
                      { group: '55岁以上', positive: 52, neutral: 33, negative: 15, count: 156 }
                    ]" style="width: 100%">
                      <el-table-column prop="group" label="用户群体" width="180" />
                      <el-table-column prop="count" label="样本数" width="100" />
                      <el-table-column label="情感分布">
                        <template #default="scope">
                          <div class="stacked-progress">
                            <div class="stacked-segment positive" :style="{ width: scope.row.positive + '%' }">
                              {{ scope.row.positive }}%
                            </div>
                            <div class="stacked-segment neutral" :style="{ width: scope.row.neutral + '%' }">
                              {{ scope.row.neutral }}%
                            </div>
                            <div class="stacked-segment negative" :style="{ width: scope.row.negative + '%' }">
                              {{ scope.row.negative }}%
                            </div>
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSentimentDetailDialog = false">关闭</el-button>
          <el-button type="primary" :icon="Download" @click="exportSentimentDetail">导出详情</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.sentiment-analysis-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  position: relative;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.refresh-controls {
  display: flex;
  align-items: center;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  border-radius: 4px;
}

.loading-icon {
  font-size: 40px;
  color: var(--el-color-primary);
  animation: rotating 2s linear infinite;
}

.loading-text {
  margin-top: 10px;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.filter-panel {
  margin-bottom: 20px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-item {
  margin-bottom: 15px;
}

.filter-label {
  font-weight: 500;
  margin-bottom: 8px;
}

.filter-select {
  width: 100%;
}

.content-area {
  margin-bottom: 20px;
}

.tab-content {
  padding: 15px 0;
}

.chart-card, .info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.peak-analysis {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.peak-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-radius: 6px;
  background-color: #f5f7fa;
}

.peak-item.peak {
  border-left: 4px solid #67C23A;
}

.peak-item.low {
  border-left: 4px solid #F56C6C;
}

.peak-icon {
  font-size: 24px;
  margin-right: 15px;
}

.peak-item.peak .peak-icon {
  color: #67C23A;
}

.peak-item.low .peak-icon {
  color: #F56C6C;
}

.peak-info {
  flex: 1;
}

.peak-time {
  font-weight: 500;
  margin-bottom: 5px;
}

.peak-value, .peak-change {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.anomaly-content {
  padding: 5px 0;
}

.anomaly-description {
  font-weight: 500;
  margin-bottom: 5px;
}

.anomaly-value {
  font-size: 14px;
}

.anomaly-value.positive {
  color: #67C23A;
}

.anomaly-value.negative {
  color: #F56C6C;
}

.extreme-case {
  padding: 15px;
  border-radius: 6px;
  background-color: #f5f7fa;
}

.extreme-case.positive {
  border-left: 4px solid #67C23A;
}

.extreme-case.negative {
  border-left: 4px solid #F56C6C;
}

.case-content {
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 10px;
}

.case-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.topic-sentiment-stats {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.topic-item {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.topic-name {
  font-size: 16px;
  font-weight: 500;
}

.topic-bars {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.sentiment-bar {
  display: flex;
  align-items: center;
}

.bar-label {
  width: 40px;
  margin-right: 10px;
  text-align: right;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.export-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.detail-content {
  min-height: 300px;
}

.positive-text {
  color: #67C23A;
}

.negative-text {
  color: #F56C6C;
}

.sentiment-detail-content {
  padding: 20px 0;
}

.sentiment-distribution-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.sentiment-card-title {
  font-size: 18px;
  font-weight: 600;
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--el-text-color-primary);
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.distribution-chart, .intensity-chart {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.distribution-item, .intensity-item {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 10px;
}

.distribution-label, .intensity-label {
  width: 80px;
  font-weight: 500;
  margin-right: 10px;
}

.distribution-value, .intensity-value {
  width: 100px;
  text-align: right;
  margin-right: 10px;
  color: var(--el-text-color-secondary);
}

.distribution-item :deep(.el-progress) {
  flex: 1;
  margin-top: 5px;
}

.intensity-item :deep(.el-progress) {
  flex: 1;
  margin-top: 5px;
}

.positive, .strong-positive, .moderate-positive, .mild-positive {
  color: #67C23A;
}

.neutral {
  color: #909399;
}

.negative, .strong-negative, .moderate-negative, .mild-negative {
  color: #F56C6C;
}

.strong-positive {
  color: #67C23A;
}

.moderate-positive {
  color: #95D475;
}

.mild-positive {
  color: #B3E19D;
}

.mild-negative {
  color: #F9A7A7;
}

.moderate-negative {
  color: #F78989;
}

.strong-negative {
  color: #F56C6C;
}

.word-cloud-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.word-cloud-container {
  min-height: 300px;
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  border: 1px solid #ebeef5;
}

.word-cloud-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 15px;
}

.word-cloud-item {
  transition: all 0.3s;
  cursor: pointer;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: inline-block;
}

.word-cloud-item:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.word-cloud-item.positive {
  color: #67C23A;
  border: 1px solid rgba(103, 194, 58, 0.2);
}

.word-cloud-item.neutral {
  color: #909399;
  border: 1px solid rgba(144, 147, 153, 0.2);
}

.word-cloud-item.negative {
  color: #F56C6C;
  border: 1px solid rgba(245, 108, 108, 0.2);
}

.word-value {
  font-size: 12px;
  opacity: 0.7;
  margin-left: 4px;
}

.heatmap-container {
  position: relative;
  height: 800px;
  width: 100%;
  overflow: visible;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
}

.sentiment-pie-chart {
  margin-top: 20px;
  height: 300px;
}

.stacked-progress {
  height: 30px;
  width: 100%;
  display: flex;
  border-radius: 4px;
  overflow: hidden;
}

.stacked-segment {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.stacked-segment.positive {
  background-color: #67C23A;
}

.stacked-segment.neutral {
  background-color: #909399;
}

.stacked-segment.negative {
  background-color: #F56C6C;
}

.progress-legend {
  display: flex;
  justify-content: center;
  margin-top: 5px;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.legend-item::before {
  content: '';
  display: inline-block;
  width: 10px;
  height: 10px;
  margin-right: 5px;
  border-radius: 2px;
}

.legend-item.positive::before {
  background-color: #67C23A;
}

.legend-item.neutral::before {
  background-color: #909399;
}

.legend-item.negative::before {
  background-color: #F56C6C;
}

.time-distribution-chart {
  margin-top: 20px;
}

.user-group-sentiment {
  margin-top: 20px;
}

.trend-chart-container {
  position: relative;
  height: 600px;
  width: 100%;
  overflow: hidden;
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
}

.chart-controls {
  display: flex;
  align-items: center;
}

.chart-container {
  position: relative;
  width: 100%;
  height: 600px;
}
</style> 